package com.nx.biz.shopify.sdk.ShopifySdk;

import com.google.gson.Gson;
import com.nx.biz.shopify.sdk.ShopifySdk.model.bo.OrderBoRoot;
import com.nx.biz.shopify.sdk.ShopifySdk.model.bo.OrderBoV2;
import com.nx.biz.shopify.sdk.ShopifySdk.model.bo.OrderBosRoot;
import com.nx.biz.shopify.sdk.ShopifySdk.model.constant.OrderStatus;
import com.nx.biz.shopify.sdk.ShopifySdk.model.constant.UrlConstant;
import com.nx.biz.shopify.tools.HttpRestClientTool;
import com.nx.common.result.HttpClientResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderSdk {

    //    public static String urlTemplate = "https://%s.myshopify.com/admin/api/2024-04/orders.json";
//    public static String urlInst = "https://%s.myshopify.com/admin/api/2024-04/orders/%s.json";
//    public static String devStoreNo = "track-dev-0704";
//    public static String token = "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";
    protected static final Gson GSON = new Gson();

    /**
     * 查询
     */
    public List<OrderBoV2> listOrder(String shopDomain, String apiVersion, String accessToken) throws Exception {
//        String url = String.format(urlTemplate, devStoreNo);
        String url = String.format(UrlConstant.OrderRestUrl, shopDomain, apiVersion);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("X-Shopify-Access-Token", accessToken);

//        url = url + "?limit=20";
        url = url + "?status=" + OrderStatus.any;
        HttpClientResult clientResult = HttpRestClientTool.sendGet(url, "UTF-8", headers);
        OrderBosRoot orderBosRoot = GSON.fromJson(clientResult.getContent(), OrderBosRoot.class);
        return orderBosRoot.getOrders();
    }

    public OrderBoV2 getOrder(String orderId, String shopDomain, String apiVersion, String accessToken) throws Exception {
//        String url = String.format(urlInst, devStoreNo, orderId);
        String url = String.format(UrlConstant.OrderInstRestUrl, shopDomain, apiVersion, orderId);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("X-Shopify-Access-Token", accessToken);
//        url = url + "?limit=20";
//        url = url + "?fulfillment_status=shipped";
        HttpClientResult clientResult = HttpRestClientTool.sendGet(url, "UTF-8", headers);
        OrderBoRoot orderBoRoot = GSON.fromJson(clientResult.getContent(), OrderBoRoot.class);
        return orderBoRoot.getOrder();
    }
}
